home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: allocating unlimited string input....HELP
- Date: 11 Jan 1996 21:09:44 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4d4ft8$o7i@umbc9.umbc.edu>
- References: <4cvph6$s8s@pulp.ucs.ualberta.ca>
- NNTP-Posting-Host: f-umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Bobby Sixkiller <ryangall@gpu.srv.ualberta.ca> wrote:
- |> I am doing an assignment for my computing class, and seem to have run into
- |> a small problem. I am supposed to be able to read an unlimited string from
- |> stdin, without defining maximum size. I thought that this problem would be
- |> simple....but I have been at it for a while now. Ill show you what my last
- |> resort was.....
-
- Obviously an unlimited string is impossible since computers have a finite
- amount of memory. However, I think I know what you mean.
-
- <code deleted>
-
- |> I know its ugly, but its the third version....and I tried all the other
- |> possibilities that I know of that would have better style. Anyways, they
- |> all pretty much are doing the same thing...oh yeah, about char *S, thats
- |> for later, Im still stuck trying to get the bulk of the function to work,
- |> once its working, I will assign A to S........
-
- Even if you did assign A to S in C variables are pass by value, so it
- would mean nothing. Returning the allocated string is a much nicer
- approach.
-
- |> Anyways, the function reads in just fine, but for some reason when it gets
- |> to 146 characters it bails out, loses char *B and starts reducing
- |> count?!&*#$@ what the hell?!
-
- You code seemed to work fine for me. The only thing I can think of is either
- on your machine 146 is the most amount of characters that can be on one
- command line, i.e. you gave '\n' as the condition to stop, or free()
- isn't doing a good job.
-
- Here's a solution that uses realloc() instead of malloc()/free(). It's
- not the most efficient solution, but it should get you started.
-
- char *read (void)
- {
- int c = '\0';
- int len = 0;
- char *str = NULL;
-
- do {
- if ((str = realloc (str, ++len)) == NULL)
- exit (1);
- if (c != '\0')
- str[len - 2] = (char) c;
- str[len - 1] = '\0';
- } while ((c = getchar ()) != '\n');
-
- return (str);
- }
-
- Just make sure you #include <stdio.h> and #include <stdlib.h>.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-